package com.zxq.modbus;

import com.zxq.modbus.dispatch.ModBusHandler;
import com.zxq.modbus.dispatch.SFModBusRegisterHandler;
import com.zxq.modbus.container.ModBusChannelContainer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ModBusSplitHandler extends ByteToMessageDecoder {

    ModBusHandler modBusHandler = new ModBusHandler();
    SFModBusRegisterHandler modBusRegisterHandler = new SFModBusRegisterHandler();
    /**
     * 分发不同的通信协议
     * @param channelHandlerContext 通道
     * @param byteBuf 缓存
     * @param list 转移的数据对象
     */
    //分发不同的通信协议
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        modBusHandler.injectByteBuf(channelHandlerContext,byteBuf);
        modBusRegisterHandler.injectByteBuf(channelHandlerContext,byteBuf);
        modBusRegisterHandler.next = modBusHandler;
        modBusRegisterHandler.handlerFrame();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        // ChannelContainer.getChannel()
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ModBusChannelContainer.removeChannel(ctx);
    }


}
